<?php

include('config.php');

function check_security($levels) {
    if (!is_array($levels))
        $levels = array($levels);
    if (!base_obj::security($levels)) {
        $result = array();
        $result['result'] = 0;
        $result['error'] = NO_RIGHTS;
        echo json_encode($result);
        exit;
    }
}

switch ($_REQUEST['action']) {
    case 'checkLogin':
        check_security('public');
        $result = array();
        if (empty($_REQUEST['params']['username']) || empty($_REQUEST['params']['password'])) {
            $result['result'] = 0;
            $result['error'] = EMPTY_LOGIN;
            echo json_encode($result);
        } else {
            $result['result'] = 1;
            echo json_encode($result);
        }
        break;
    case 'checkAdd_task':
        check_security(array('admin', 'client', 'technic'));
        $result = array();
        $task_obj = new task_obj();
        $res = $task_obj->checkAdd_task($_REQUEST['params']);
        if (empty($res)) {
            $result['result'] = 1;
            $result['bad_fields'] = array();
            echo json_encode($result);
        } else {
            $result['result'] = 0;
            $result['bad_fields'] = $res;
            $result['error'] = EMPTY_REQUIRED_FIELD;
            echo json_encode($result);
        }
        break;
    case 'changeRecords_per_page':
        check_security(array('admin', 'client', 'technic'));
        $result = array();
        $_SESSION[$_REQUEST['params']['variable']] = $_REQUEST['params']['records'];
        $result['result'] = 1;
        echo json_encode($result);
        break;
    case 'changeOrderOfRows':
        check_security(array('admin', 'client', 'technic'));
        $result = array();
        if ($_REQUEST['params']['order'] == 'CLEAR') {
            $_SESSION[$_REQUEST['params']['variable']] = $GLOBALS[$_REQUEST['params']['variable']];
        } else {

            $col = $orderBy = $_REQUEST['params']['order'];
            $table = $connector = '';
            if ($_REQUEST['params']['order'] == 'client') {
                $orderBy = 'name';
                $table = $GLOBALS['tb_clients'];
                $connector = $col . '=' . $table . '.klient_id';
            } elseif (($_REQUEST['params']['order'] == 'contactPerson') || ($_REQUEST['params']['order'] == 'user') || ($_REQUEST['params']['order'] == 'who_added') || ($_REQUEST['params']['order'] == 'user_id') || ($_REQUEST['params']['order'] == 'responsible') || ($_REQUEST['params']['order'] == 'worker') || ($_REQUEST['params']['order'] == 'creator') || ($_REQUEST['params']['order'] == 'updater')) {
                $orderBy = 'surname';
                $table = $GLOBALS['tb_users'];
                $connector = $col . '=' . $table . '.users_id';
            } elseif (($_REQUEST['params']['variable'] == 'list_of_tasks_order' || $_REQUEST['params']['variable'] == 'timesheets_order') && ($_REQUEST['params']['order'] == 'type')) {
                $orderBy = 'type_of_record';
                $table = $GLOBALS['tb_type_of_records'];
                $connector = $col . '=' . $table . '.Id';
            } elseif (($_REQUEST['params']['order'] == 'status')) {
                $orderBy = 'stav';
                $table = $GLOBALS['tb_task_statuses'];
                $connector = $col . '=' . $table . '.id_stav';
            } elseif (($_REQUEST['params']['variable'] != 'list_of_tariffs_order') && ($_REQUEST['params']['order'] == 'tariff')) {
                $orderBy = 'title';
                $table = $GLOBALS['tb_tariffs'];
                $connector = $col . '=' . $table . '.Id';
            } elseif (($_REQUEST['params']['order'] == 'type_of_move')) {
                $orderBy = 'TypPohybu';
                $table = $GLOBALS['tb_type_of_cash_move'];
                $connector = $col . '=' . $table . '.Id';
            } elseif (($_REQUEST['params']['order'] == 'type_of_cooperation')) {
                $orderBy = 'type';
                $table = $GLOBALS['tb_type_of_cooperations'];
                $connector = $col . '=' . $table . '.id';
            } elseif (($_REQUEST['params']['order'] == 'userlevel')) {
                $orderBy = 'level';
                $table = $GLOBALS['tb_userslevels'];
                $connector = $col . '=' . $table . '.levelId';
            }

            if (empty($_SESSION[$_REQUEST['params']['variable']])) {
                $order = 'DESC';
            } else {
                $oldCol = $_SESSION[$_REQUEST['params']['variable']]['col'];
                $oldOrder = $_SESSION[$_REQUEST['params']['variable']]['order'];
                if ($oldCol != $col) {
                    $order = 'DESC';
                } elseif (($oldCol == $col) && ($oldOrder == 'DESC')) {
                    $order = 'ASC';
                } else {
                    $order = 'DESC';
                }
            }

            $_SESSION[$_REQUEST['params']['variable']] = array(
                'col' => $col,
                'orderBy' => $orderBy,
                'order' => $order,
                'table' => $table,
                'connector' => $connector
            );
        }
        $result['result'] = 1;
        echo json_encode($result);
        break;
    case 'addFilter':
        check_security(array('admin', 'client', 'technic'));
        $result = array();

        if (!isset($_SESSION[$_REQUEST['params']['variable']])) {
            $_SESSION[$_REQUEST['params']['variable']] = array();
        }

        $_SESSION[$_REQUEST['params']['variable']][$_REQUEST['params']['filter']] = $_REQUEST['params']['value'];

        $result['result'] = 1;
        echo json_encode($result);
        break;
    case 'cancelFilter':
        check_security(array('admin', 'client', 'technic'));
        $result = array();

        unset($_SESSION[$_REQUEST['params']['variable']][$_REQUEST['params']['filter']]);
        //$_SESSION[$_REQUEST['params']['variable']][$_REQUEST['params']['filter']] = null;

        $result['result'] = 1;
        echo json_encode($result);
        break;
    case 'setFulltext':
        check_security(array('admin', 'client', 'technic'));
        $result = array();

        if (!isset($_SESSION[$_REQUEST['params']['variable']])) {
            $_SESSION[$_REQUEST['params']['variable']] = '';
        }

        $_SESSION[$_REQUEST['params']['variable']] = strip_tags(trim($_REQUEST['params']['search']));

        $result['result'] = 1;
        echo json_encode($result);
        break;
    case 'cancelFulltext':
        check_security(array('admin', 'client', 'technic'));
        $result = array();

        unset($_SESSION[$_REQUEST['params']['variable']]);

        $result['result'] = 1;
        echo json_encode($result);
        break;
    case 'deleteTask':
        check_security(array('admin'));
        $result = array();
        $task_obj = new task_obj();
        $res = $task_obj->deleteTask($_REQUEST['params']['taskId']);
        if (error_obj::isError($res)) {
            $result['result'] = 0;
        } else {
            $result['result'] = 1;
        }
        echo json_encode($result);
        break;
    case 'deletePost':
        check_security(array('admin', 'client', 'technic'));
        $result = array();
        $task_phorum_obj = new task_phorum_obj();
        $res = $task_phorum_obj->deletePostById($_REQUEST['params']['postId']);
        if (error_obj::isError($res)) {
            $result['result'] = 0;
        } else {
            $result['result'] = 1;
        }
        echo json_encode($result);
        break;
    case 'deleteRecordPost':
        check_security(array('admin', 'client', 'technic'));
        $result = array();
        $record_phorum_obj = new record_phorum_obj();
        $res = $record_phorum_obj->deletePostById($_REQUEST['params']['postId']);
        if (error_obj::isError($res)) {
            $result['result'] = 0;
        } else {
            $result['result'] = 1;
        }
        echo json_encode($result);
        break;
    case 'getPostData':
        check_security(array('admin', 'client', 'technic'));
        $result = array();
        $task_phorum_obj = new task_phorum_obj();
        $res = $task_phorum_obj->getPostById($_REQUEST['params']['postId']);
        $res['text'] = htmlspecialchars_decode($res['text']);
        if (error_obj::isError($res)) {
            $result['post'] = $res;
            $result['result'] = 0;
        } else {
            $result['post'] = $res;
            $result['result'] = 1;
        }
        echo json_encode($result);
        break;
    case 'getRecordPostData':
        check_security(array('admin', 'client', 'technic'));
        $result = array();
        $record_phorum_obj = new record_phorum_obj();
        $res = $record_phorum_obj->getPostById($_REQUEST['params']['postId']);
        $res['text'] = htmlspecialchars_decode($res['text']);
        if (error_obj::isError($res)) {
            $result['post'] = $res;
            $result['result'] = 0;
        } else {
            $result['post'] = $res;
            $result['result'] = 1;
        }
        echo json_encode($result);
        break;
    case 'checkAdd_client':
        check_security(array('admin'));
        $result = array();
        $client_obj = new client_obj();
        $res = $client_obj->checkAdd_client($_REQUEST['params']);
        if (empty($res)) {
            $result['result'] = 1;
            $result['bad_fields'] = array();
            echo json_encode($result);
        } else {
            $result['result'] = 0;
            $result['bad_fields'] = $res;
            $result['error'] = EMPTY_REQUIRED_FIELD;
            echo json_encode($result);
        }
        break;
    case 'checkAdd_user':
        check_security(array('admin', 'technic'));
        $result = array();
        $user_obj = new user_obj();
        $res = $user_obj->checkAdd_user($_REQUEST['params']);
        if (empty($res)) {
            $result['result'] = 1;
            $result['bad_fields'] = array();
            echo json_encode($result);
        } else {
            $result['result'] = 0;
            $result['bad_fields'] = $res;
            $result['error'] = EMPTY_REQUIRED_FIELD;
            echo json_encode($result);
        }
        break;
    case 'checkAdd_entry':
        check_security(array('admin', 'technic'));
        $result = array();
        $cash_obj = new cash_obj();
        $res = $cash_obj->checkAdd_entry($_REQUEST['params']);
        if (empty($res)) {
            $result['result'] = 1;
            $result['bad_fields'] = array();
            echo json_encode($result);
        } else {
            $result['result'] = 0;
            $result['bad_fields'] = $res;
            $result['error'] = EMPTY_BAD_REQUIRED_FIELD;
            echo json_encode($result);
        }
        break;
    case 'filter_clients_by_fulltext':
        check_security(array('admin', 'technic'));
        $result = array();
        $client_obj = new client_obj();
        $res = $client_obj->getClientByName($_REQUEST['params']['client'], 'ORDER BY name ASC', 'LIMIT 0,5');
        if (error_obj::isError($res)) {
            $result['data'] = $res;
            $result['result'] = 0;
        } else {
            $result['data'] = $res;
            $result['result'] = 1;
        }
        echo json_encode($result);
        break;
    case 'checkAdd_tariff':
        check_security(array('admin'));
        $result = array();
        $tariff_obj = new tariff_obj();
        $res = $tariff_obj->checkAdd_tariff($_REQUEST['params']);
        if (empty($res)) {
            $result['result'] = 1;
            $result['bad_fields'] = array();
            echo json_encode($result);
        } else {
            $result['result'] = 0;
            $result['bad_fields'] = $res;
            $result['error'] = EMPTY_BAD_REQUIRED_FIELD;
            echo json_encode($result);
        }
        break;
    case 'show_monthly_report_of_client':
        check_security(array('admin', 'technic'));
        $result = array();
        $month = date("m");
        $year = date("Y");
        $client_obj = new client_obj();
        $db_obj = new db_obj();
        $res = $client_obj->getClient($_REQUEST['params']['client'], array('conditions'));

        $text = '';

        if (!error_obj::isError($res) && !empty($res)) {
            $text .= '<div><h3>Conditions:</h3>';
            if (empty($res['conditions']))
                $text .= '-';
            else
                $text .= $res['conditions'];
            $text .= '</div>';
        }

        $sql = "SELECT SUM(amount) AS s FROM " . $GLOBALS['tb_records'] . " WHERE client=" . $_REQUEST['params']['client'] . " AND DATE_FORMAT(date, '%m')='" . $month . "' AND DATE_FORMAT(date, '%Y')='" . $year . "'";
        $res = $db_obj->getOne($sql);
        if (!error_obj::isError($res) && !empty($res)) {
            $text .= '<div><h3>Used amount in ' . $month . '/' . $year . ':</h3>';
            $text .= $res;
            $text .= '</div>';
        } else {
            $text .= '<div><h3>Used amount in ' . $month . '/' . $year . ':</h3>';
            $text .= '0';
            $text .= '</div>';
        }

        $result['text'] = $text;
        $result['result'] = 1;

        echo json_encode($result);
        break;
    case 'change_tariffs':
        check_security(array('admin', 'technic'));
        $result = array();
        $tariff_obj = new tariff_obj();
        $filter = array();
        $filter['type_of_record'] = $_REQUEST['params']['type'];
        $order = array(
            'col' => 'title',
            'orderBy' => 'title',
            'order' => 'ASC',
            'table' => '',
            'connector' => ''
        );
        $res = $tariff_obj->getTariffs("Id, title", $filter, $order);
        if (error_obj::isError($res) || empty($res)) {
            $result['result'] = 0;
            echo json_encode($result);
        } else {
            $result['result'] = 1;
            $result['options'] = '';
            foreach ($res as $key => $tariff) {
                $result['options'] .= '<option value="' . $tariff['Id'] . '">' . $tariff['title'] . '</option>';
            }
            echo json_encode($result);
        }
        break;
    case 'fill_price':
        check_security(array('admin', 'technic'));
        $result = array();
        $tariff_obj = new tariff_obj();
        $res = $tariff_obj->getTariffById($_REQUEST['params']['tariff']);
        if (error_obj::isError($res) || empty($res)) {
            $result['result'] = 0;
            echo json_encode($result);
        } else {
            $result['result'] = 1;
            $result['price'] = $res['tariff'];
            echo json_encode($result);
        }
        break;
    case 'checkAdd_record':
        check_security(array('admin', 'technic'));
        $result = array();
        $record_obj = new record_obj();
        $res = $record_obj->checkAdd_record($_REQUEST['params']);
        if (empty($res)) {
            $result['result'] = 1;
            $result['bad_fields'] = array();
            echo json_encode($result);
        } else {
            $result['result'] = 0;
            if (in_array('amount_count', $res)) {
                unset($res['amount_count']);
                if (!in_array('amount', $res))
                    $res[] = 'amount';
                $result['error'] = EMPTY_BAD_REQUIRED_FIELD_OF_RECORD_REACHED_LIMIT;
            } else {
                $result['error'] = EMPTY_BAD_REQUIRED_FIELD_OF_RECORD;
            }
            $result['bad_fields'] = $res;
            echo json_encode($result);
        }
        break;
    case 'deleteRecord':
        check_security(array('admin', 'technic'));
        $result = array();
        $record_obj = new record_obj();
        $record = $record_obj->getRecordById($_REQUEST['params']['recordId']);
        if (error_obj::isError($record) || empty($record)) {
            $result['result'] = 0;
        } else {
            $lock_obj = new lock_obj();
            if ($lock_obj->isRecordLocked(base_obj::convertDateTo($record['date'], "dd/mm/yyyy", 'date'))) {
                $result['result'] = 0;
                $result['locked'] = 1;
            } else {
                $res = $record_obj->deleteRecordById($_REQUEST['params']['recordId']);
                if (error_obj::isError($res)) {
                    $result['result'] = 0;
                } else {
                    if (isset($_SESSION['request']['newRecords'][$_REQUEST['params']['recordId']])) {
                        unset($_SESSION['request']['newRecords'][$_REQUEST['params']['recordId']]);
                    }
                    $result['result'] = 1;
                }
            }
        }
        echo json_encode($result);
        break;
    case 'changeClientFilter':
        check_security(array('admin', 'technic'));
        $result = array();
        if ($_REQUEST['params']['value'] == 0 && isset($_SESSION['user']['clientFilter']))
            unset($_SESSION['user']['clientFilter']);
        elseif ($_REQUEST['params']['value'] != 0)
            $_SESSION['user']['clientFilter'] = $_REQUEST['params']['value'];

        $filter_obj = new filter_obj();
        $filter_obj->setClientToEachFilter($_REQUEST['params']['value']);

        if ($_REQUEST['params']['remember'] == 0 && isset($_SESSION['user']['rememberClientFilter']))
            unset($_SESSION['user']['rememberClientFilter']);
        elseif ($_REQUEST['params']['remember'] != 0) {
            $_SESSION['user']['rememberClientFilter'] = $_REQUEST['params']['value'];
            $user_obj = new user_obj();
            $in_options = array(
                'userId' => $_SESSION['user']['user_id'],
                'clientFilter' => $_REQUEST['params']['value']
            );
            $res = $user_obj->setUserOptions($in_options);
        }

        $result['result'] = 1;
        echo json_encode($result);
        break;
    case 'rememberClientFilter':
        check_security(array('admin', 'technic'));
        if ($_REQUEST['params']['remember'] == 0)
            $clientFilter = 0;
        else
        if (!isset($_SESSION['user']['clientFilter']))
            $clientFilter = 0;
        else
            $clientFilter = $_SESSION['user']['clientFilter'];

        if ($_REQUEST['params']['remember'] == 0 && isset($_SESSION['user']['rememberClientFilter']))
            unset($_SESSION['user']['rememberClientFilter']);
        else
            $_SESSION['user']['rememberClientFilter'] = $clientFilter;

        $user_obj = new user_obj();
        $in_options = array(
            'userId' => $_SESSION['user']['user_id'],
            'clientFilter' => $clientFilter
        );
        $res = $user_obj->setUserOptions($in_options);
        $result['result'] = 1;
        echo json_encode($result);
        break;
    case 'userListOfClient':
        check_security(array('admin', 'technic', 'client'));
        
        if ($_SESSION['user']['profile']['userlevel'] == USER_TYPE_CLIENT) 
            if(!isset($_SESSION['user']['clients'][$_REQUEST['params']['client']]))
                check_security(array('admin', 'technic'));
        $result = array();
        $user_obj = new user_obj();
        $f = array(
            'userlevel' => USER_TYPE_CLIENT,
            'client' => $_REQUEST['params']['client']
        );
        $res = $user_obj->getUsers('users_id, surname, name, prefered', $f);
        if (error_obj::isError($res)) {
            $result['result'] = 0;
        } else {
            $result['options'] = '';
            if (!empty($res)) {
                foreach ($res as $key => $value) {
                    if ($value['prefered'] == 1)
                        $selected = 'selected="selected"';
                    else
                        $selected = '';
                    $result['options'] .= '<option ' . $selected . ' value="' . $value['users_id'] . '">' . $value['name'] . ' ' . $value['surname'] . '</option>';
                }
            }
            $result['result'] = 1;
        }
        echo json_encode($result);
        break;
    case 'taskListOfClient':
        check_security(array('admin', 'technic', 'client'));
        
        if ($_SESSION['user']['profile']['userlevel'] == USER_TYPE_CLIENT) 
            if(!isset($_SESSION['user']['clients'][$_REQUEST['params']['client']]))
                check_security(array('admin', 'technic'));
            
        $result = array();
        $task_obj = new task_obj();
        $f = array(
            'client' => $_REQUEST['params']['client']
        );
        $order = array(
            'col' => 'created',
            'orderBy' => 'created',
            'order' => 'DESC',
            'table' => '',
            'connector' => ''
        );
        $res = $task_obj->getListOfTasks($f, $order);
        if (error_obj::isError($res)) {
            $result['result'] = 0;
        } else {
            $result['options'] = '';
            if (!empty($res)) {
                foreach ($res as $key => $value) {
                    $result['options'] .= '<option value="' . $value['taskId'] . '">' . $value['title'] . '</option>';
                }
            }
            $result['result'] = 1;
        }
        echo json_encode($result);
        break;
    case 'deleteEntry':
        check_security(array('admin'));
        $result = array();
        $cash_obj = new cash_obj();
        $cash = $cash_obj->getEntry($_REQUEST['params']['entryId']);
        if (error_obj::isError($cash) || empty($cash)) {
            $result['result'] = 0;
        } else {
            $lock_obj = new lock_obj();
            if ($lock_obj->isEntryLocked(base_obj::convertDateTo($cash['date'], "dd/mm/yyyy", 'date'))) {
                $result['result'] = 0;
                $result['locked'] = 1;
            } else {
                $res = $cash_obj->deleteEntryById($_REQUEST['params']['entryId']);
                if (error_obj::isError($res)) {
                    $result['result'] = 0;
                } else {
                    $result['result'] = 1;
                }
            }
        }
        echo json_encode($result);
        break;
    case 'fillDescription':
        check_security(array('admin', 'technic'));
        $result = array();
        $tariff_obj = new tariff_obj();
        $tariff = $tariff_obj->getTariffById($_REQUEST['params']['tariffId']);
        if (error_obj::isError($tariff) || empty($tariff)) {
            $result['result'] = 0;
        } else {
            $result['result'] = 1;
            $result['title'] = $tariff['title'];
        }
        echo json_encode($result);
        break;
    case 'unexpended':
        check_security(array('admin', 'technic'));
        $result = array();

        $record_obj = new record_obj();
        $res = $record_obj->get_monthly_unexpended_by_client($_REQUEST['params']['date'], $_REQUEST['params']['client']);

        if (error_obj::isError($res)) {
            $result['result'] = 0;
            $result['value'] = 'Incorrect date or client';
        } else {
            $result['value'] = $res;
            $result['result'] = 1;
        }

        echo json_encode($result);
        break;
    case 'checkAdd_expense':
        check_security(array('admin'));
        $result = array();
        $expense_obj = new expense_obj();
        $res = $expense_obj->checkAdd_expense($_REQUEST['params']);
        if (empty($res)) {
            $result['result'] = 1;
            $result['bad_fields'] = array();
            echo json_encode($result);
        } else {
            $result['result'] = 0;
            $result['bad_fields'] = $res;
            $result['error'] = EMPTY_REQUIRED_FIELD;
            echo json_encode($result);
        }
        break;
    case 'getRentabilityTablePerServismen':
        check_security(array('admin'));
        $result = array();

        $data = array();

        $db_obj = new db_obj();
        $task_obj = new task_obj();
        $client_obj = new client_obj();
        $record_obj = new record_obj();
        $user_obj = new user_obj();
        $expense_obj = new expense_obj();
        $tariff_obj = new tariff_obj();

        $task_data = $task_obj->getTaskById($_REQUEST['params']['taskId']);
        $client = $client_obj->getClient($task_data['client']);
        $task_data['client_info'] = $client;
        $task_data['added_formated'] = base_obj::convertDateTo($task_data['added'], "dd/mm/yyyy H:i:s", 'datetime');
        $task_data['updated_formated'] = base_obj::convertDateTo($task_data['updated'], "dd/mm/yyyy H:i:s", 'datetime');

        // zistenie poctu aktivnych mesiacov, napr ak uloha aktivna od 1.maja do 15.jula = 3
        $task_data['count_of_active_months'] = $task_obj->getCountOfActiveMonths($task_data['added'], $task_data['updated']);
        // vygenerovanie pola dvojic mesiac, rok - aktivne mesiace z Tasku
        $task_data['active_months_task'] = $task_obj->getArrayOfMonths($task_data['added'], $task_data['count_of_active_months']);
        // vygenerovanie pola dvojic mesiac, rok - aktivne mesiace z TSDR
        $task_data['active_months_records'] = $record_obj->getActiveMonths($task_data['taskId']);
        // zmergovanie mesiacov z tasku a z jeho TSDR
        $task_data['active_months'] = array_merge($task_data['active_months_task'], $task_data['active_months_records']);

        $filter = array(
            'taskId' => $task_data['taskId'],
            'nottariff' => 6,
            'nottype' => 8
        );
        $task_data['active_servismen'] = $record_obj->getListOfRecords($filter, array(), '', 'user_id', 'user_id'); // pole id servisakov

        $data['task_data'] = $task_data;
        //prechadzam servisakov
        $rows = array();
        $data['sum_hours'] = 0;
        $data['sum_hour_expense'] = 0;
        $data['sum_first'] = 0;
        $data['sum_second'] = 0;
        $data['sum_third'] = 0;
        foreach ($task_data['active_servismen'] as $servisman) {

            $servisman_data = array();
            $servisman_data['user_data'] = $user_obj->getUserById($servisman['user_id']);

            $servisman_data['sum_hours'] = 0;
            $servisman_data['sum_hour_expense'] = 0;
            $servisman_data['first'] = 0;
            $servisman_data['second'] = 0;
            $servisman_data['third'] = 0;

            foreach ($task_data['active_months'] as $month) {

                // zistenie fixnych nakladov daneho servisaka
                $fixed = $expense_obj->getExpenseInPeriodByUser($servisman['user_id'], ($month[1] . '-' . $month[0] . '-1'));
                // zistenie kolko casu bol servisak v danom mesiac na danej ulohe, okrem pravidelneho servisu
                $hours_on_task_per_servisman = $expense_obj->get_hours_per_servisman_on_task($servisman['user_id'], $month[0], $month[1], $task_data['taskId']);
                // zistenie kolko casu bol servisak v danom mesiac na vsetkych ulohach, okrem pravidelneho servisu
                $hours_per_servisman = $expense_obj->get_hours_per_servisman($servisman['user_id'], $month[0], $month[1]);

                // vypocet prvej casti nakladov: fixne naklady * cas na ulohe / celkovy cas
                if (!empty($hours_per_servisman)) {
                    $servisman_data['first'] += ($fixed * $hours_on_task_per_servisman / $hours_per_servisman);
                }

                // ak ma klient nastavenu zodpovednu osobu a je to dany servisak
                if (!empty($client['contactPerson']) && ($client['contactPerson'] == $servisman['user_id'])) {
                    // zistenie kolko casu bol zodpovedny na danej ulohe v danom mesiaci, okrem pravidelneho servisu
                    $hours_on_task_per_responsible = $expense_obj->get_hours_per_responsible_on_task($task_data['taskId'], $client['klient_id'], $servisman['user_id'], $month[0], $month[1]);
                    // zistenie kolko casu bol zodpovedny na ulohach pre daneho klienta v danom mesiaci, okrem pravidelneho servisu
                    $hours_per_responsible = $expense_obj->get_hours_per_servisman($servisman['user_id'], $month[0], $month[1]);

                    // vypocet druhej casti nakladov: mesacna poplatok od klienta * cas zodpovedneho na ulohe / celkovy cas zodpovedneho na ulohach klienta
                    if (!empty($hours_per_responsible)) {
                        $servisman_data['second'] += ($client['monthlyFee'] * $hours_on_task_per_responsible / $hours_per_responsible);
                    }
                }

                // ziskanie TSDR zaznamov
                $records = $expense_obj->get_records_per_servisman_on_task($task_data['taskId'], $month[0], $month[1], $servisman['user_id'], true);

                // vypocet tretej casti nakladov: suma sucinov casu na ulohe a odmeny pre servisaka
                foreach ($records as $record) {
                    $servisman_data['sum_hours'] += $record['amount'];
                    $servis_tariff = $tariff_obj->getTariffById($record['tariff'], array('servis_tariff'));
                    $servisman_data['third'] += ($servis_tariff['servis_tariff'] * $record['amount']);
                }
            }

            $servisman_data['sum'] = $servisman_data['first'] + $servisman_data['second'] + $servisman_data['third'];
            if (!empty($servisman_data['sum_hours']))
                $servisman_data['sum_hour_expense'] = $servisman_data['sum'] / $servisman_data['sum_hours'];
            else
                $servisman_data['sum_hour_expense'] = '-';
            $data['sum_hours'] += $servisman_data['sum_hours'];
            $data['sum_first'] += $servisman_data['first'];
            $data['sum_second'] += $servisman_data['second'];
            $data['sum_third'] += $servisman_data['third'];
            $rows[] = $servisman_data;
        }
        $data['sum'] = $data['sum_first'] + $data['sum_second'] + $data['sum_third'];

        $data['rows'] = $rows;

        // ziskanie TSDR zaznamov pre tovar
        $f = array(
            'taskId' => $task_data['taskId'], // dana uloha 
            'tariff' => 32 // tariff tovar
        );
        $data['goods'] = $record_obj->getListOfRecords($f);

        $GLOBALS['smarty']->template_dir = PATH_TO_TEMPLATES . 'includes/';
        $GLOBALS['smarty']->assign("data", $data);

        $result['data'] = $data;
        $result['output'] = $GLOBALS['smarty']->fetch('overlay_table.tpl');
        $result['result'] = 1;
        echo json_encode($result);
        break;
    case 'getRentabilityTablePerTasks':
        check_security(array('admin'));
        $result = array();

        $data = array();

        $db_obj = new db_obj();
        $task_obj = new task_obj();
        $client_obj = new client_obj();
        $record_obj = new record_obj();
        $user_obj = new user_obj();
        $expense_obj = new expense_obj();
        $tariff_obj = new tariff_obj();

        $data = array();
        $data['period'] = $_REQUEST['params']['period'];

        $period = explode('/', $_REQUEST['params']['period']);

        $user = $user_obj->getUserById($_REQUEST['params']['userId']);
        $data['user'] = $user;

        $order = array(
            'col' => 'updated',
            'orderBy' => 'updated',
            'order' => 'ASC',
            'table' => '',
            'connector' => ''
        );

        $f = array(
            'status' => COMPLETED_TASK,
            'updated_month' => (int) $period[0],
            'updated_year' => $period[1]
        );
        $tasks = $task_obj->getListOfTasks($f, $order);
        
        $data['sum'] = 0;
        $data['sum_z1'] = 0;
        $data['sum_z2'] = 0;
        $data['sum_z3'] = 0;

        foreach ($tasks as $key => $task) {
            // ziskanie zucastnenych servisakov
            $filter = array(
                'taskId' => $task['taskId'],
                'nottariff' => 6,
                'nottype' => 8
            );
            $tasks[$key]['active_servismen'] = $record_obj->getListOfRecords($filter, array(), '', 'user_id', 'user_id'); // pole id servisakov
            // zistenie ci je pozadovany servisak medzi aktivnymi na danej ulohe
            $temp = array();
            foreach ($tasks[$key]['active_servismen'] as $s_key => $s_value) {
                $temp[$s_value['user_id']] = $s_value['user_id'];
            }

            if (!isset($temp[$_REQUEST['params']['userId']]) || empty($temp[$_REQUEST['params']['userId']])) {
                unset($tasks[$key]);
                continue;
            }

            $tasks[$key]['count_of_active_servismen'] = count($tasks[$key]['active_servismen']); // pocet servisakov
            //ziskanie dat o klientovi z ulohy
            $client = $client_obj->getClient($task['client']);
            $tasks[$key]['client_info'] = $client;
            $tasks[$key]['added_formated'] = base_obj::convertDateTo($task['added'], "dd/mm/yyyy H:i:s", 'datetime');
            $tasks[$key]['updated_formated'] = base_obj::convertDateTo($task['updated'], "dd/mm/yyyy H:i:s", 'datetime');
            // zistenie poctu aktivnych mesiacov, napr ak uloha aktivna od 1.maja do 15.jula = 3
            $tasks[$key]['count_of_active_months'] = $task_obj->getCountOfActiveMonths($task['added'], $task['updated']);
            // vygenerovanie pola dvojic mesiac, rok - aktivne mesiace z Tasku
            $tasks[$key]['active_months_task'] = $task_obj->getArrayOfMonths($task['added'], $tasks[$key]['count_of_active_months']);
            // vygenerovanie pola dvojic mesiac, rok - aktivne mesiace z TSDR
            $tasks[$key]['active_months_records'] = $record_obj->getActiveMonths($task['taskId']);
            // zmergovanie mesiacov z tasku a z jeho TSDR
            $tasks[$key]['active_months'] = array_merge($tasks[$key]['active_months_task'], $tasks[$key]['active_months_records']);

            // nainicializovanie zaciatocnych hodnot
            $tasks[$key]['z1'] = 0;
            $tasks[$key]['z2'] = 0;
            $tasks[$key]['z3'] = 0;
            
            // prechadzam aktivne mesiace
            foreach ($tasks[$key]['active_months'] as $month) {

                $fixed = $expense_obj->getExpenseInPeriodByUser($_REQUEST['params']['userId'], ($month[1] . '-' . $month[0] . '-1'));
                // zistenie kolko casu bol servisak v danom mesiac na danej ulohe, okrem pravidelneho servisu
                $hours_on_task_per_servisman = $expense_obj->get_hours_per_servisman_on_task($_REQUEST['params']['userId'], $month[0], $month[1], $task['taskId']);
                // zistenie kolko casu bol servisak v danom mesiac na vsetkych ulohach, okrem pravidelneho servisu
                $hours_per_servisman = $expense_obj->get_hours_per_servisman($_REQUEST['params']['userId'], $month[0], $month[1]);

                // vypocet prvej casti nakladov: fixne naklady * cas na ulohe / celkovy cas
                if (!empty($hours_per_servisman)) {
                    $tasks[$key]['z1'] += ($fixed * $hours_on_task_per_servisman / $hours_per_servisman);
                }

                // ak ma klient nastavenu zodpovednu osobu
                if (!empty($client['contactPerson']) && ($client['contactPerson'] == $_REQUEST['params']['userId'])) {
                    // zistenie kolko casu bol zodpovedny na danej ulohe v danom mesiaci, okrem pravidelneho servisu
                    $hours_on_task_per_responsible = $expense_obj->get_hours_per_responsible_on_task($task['taskId'], $client['klient_id'], $client['contactPerson'], $month[0], $month[1]);
                    // zistenie kolko casu bol zodpovedny na ulohach pre daneho klienta v danom mesiaci, okrem pravidelneho servisu
                    $hours_per_responsible = $expense_obj->get_hours_per_responsible($client['klient_id'], $client['contactPerson'], $month[0], $month[1]);

                    // vypocet druhej casti nakladov: mesacna poplatok od klienta * cas zodpovedneho na ulohe / celkovy cas zodpovedneho na ulohach klienta
                    if (!empty($hours_per_responsible)) {
                        $tasks[$key]['z2'] += ($client['monthlyFee'] * $hours_on_task_per_responsible / $hours_per_responsible);
                    }
                }

                $records = $expense_obj->get_records_per_servisman_on_task($task['taskId'], $month[0], $month[1], $_REQUEST['params']['userId'], true);

                // vypocet tretej casti nakladov: suma sucinov casu na ulohe a odmeny pre servisaka
                foreach ($records as $record) {
                    $servis_tariff = $tariff_obj->getTariffById($record['tariff'], array('servis_tariff'));
                    $tasks[$key]['z3'] += ($servis_tariff['servis_tariff'] * $record['amount']);
                }
            }
            
            $tasks[$key]['expense'] = $tasks[$key]['z1'] + $tasks[$key]['z2'] + $tasks[$key]['z3'];
            $data['sum_z1'] += $tasks[$key]['z1'];
            $data['sum_z2'] += $tasks[$key]['z2'];
            $data['sum_z3'] += $tasks[$key]['z3'];
            $data['sum'] += $tasks[$key]['expense'];
        }
        
        $data['tasks'] = $tasks;

        $GLOBALS['smarty']->template_dir = PATH_TO_TEMPLATES . 'includes/';
        $GLOBALS['smarty']->assign("data", $data);

        $result['data'] = $data;
        $result['output'] = $GLOBALS['smarty']->fetch('overlay_table_servismen.tpl');
        $result['result'] = 1;
        echo json_encode($result);
        break;
}
?>
